package com.taomus.mytools.lang.clojure;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import com.taomus.mytools.lang.exception.GetClassException;
import com.taomus.mytools.lang.exception.InstanceException;
import com.taomus.mytools.lang.inter.DSLangUtils;
import com.taomus.mytools.lang.inter.IMethod;

import clojure.lang.RT;

public class ClojureUtils extends DSLangUtils {

	private final static Map<String, String> cachePool = new LinkedHashMap<>();

	public static Object eval(String script) throws InstanceException,GetClassException {
		ClojureUtils ch = new ClojureUtils();
		IMethod im = ch.newInstance("com/taomus/mytools/lang/clojure/script/CljEval.clj");
		return im.getMethod("cljEval").invoke(script);
	}
	
	@Override
	public IMethod newInstance(String name,boolean isCache) throws InstanceException,GetClassException {
		if(!name.endsWith(".clj")) {
			throw new InstanceException("Not a Clojure file");
		}
		String file = null;
		if(isCache && cachePool.containsKey(name)) {
			file = cachePool.get(name);
		}else{
			file = name.replace(".clj", "");
			cachePool.put(name, file);
		}
		try {
			RT.load(file);
		} catch (ClassNotFoundException e) {
			throw new InstanceException(e);
		} catch (IOException e) {
			throw new GetClassException(e);
		}
		return new ClojureMethod(file.replace("/", ".").replace("_", "-"));
	}

	@Override
	public Class<?> getClass(String name) {
		return null;
	}
}
